import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserRoutes, getCompanyAuth } from '@/api/user'
import { useRouteStore } from '@/pinia/tagsRoute'
import { userStore } from '@/pinia/user'
import pinia from '@/pinia/store'
import { map, routeSub } from '@/utils/pages'

const routes = [
    {
        path: '/',
        component: () => import('@/layout/index.vue'),
        name: 'layout',
        redirect: '/dashboard',
        children: [
            {
                path: '/dashboard',
                name: 'dashboard',
                component: () => import('@/views/system/dashboard.vue'),
                meta: {
                    title: '首页',
                    keepAlive: false
                }
            },
            {
                path: '/:pathMatch(.*)*',    // 捕获所有路由或 404 Not found 路由
                component: () => import('@/views/system/dashboard.vue')
            }
        ].concat(routeSub)
    },

    {
        path: '/login',
        name: 'login',
        component: () => import('../views/system/login.vue')
    },
    {
        path: '/404',
        component: () => import('@/views/system/404.vue')
    }
]


function getRoutes(menus) {
    let actionRouter = [];
    menus.forEach(item => {
        if (map.get(item.name)) {
            actionRouter.push({
                path: item.path,
                component: map.get(item.name),
                name: item.name,
                meta: {
                    title: item.title,
                    keepAlive: item.keepAlive === 'true' ? true : false
                }
            })
        }

    })
    return actionRouter;
}

const router = createRouter({
    history: createWebHashHistory(),
    routes
})




let whiteList = ['/login', '/404']
let hasRoles = true

router.beforeEach(async (to, from, next) => {


    const token = localStorage.getItem('🎈token')
    if (token) {
        if (to.path === '/login') {
            ElMessage.warning('当前已经登陆！')
            next('/')
        } else {
            const routeStore = useRouteStore(pinia)
            if (hasRoles) {
                const _userStore = userStore(pinia)
                const profile = JSON.parse(localStorage.getItem('profile'))
                const { newArr, data } = await getUserRoutes({ id: profile.userID })
                const { auth } = await getCompanyAuth({ sqlID: profile.sqlID })
                const _muen = data.reduce((curr, prev) => {
                    const children = prev.children
                    const isExist = children.some(item => map.get(item.name))
                    if (isExist) {
                        return curr.concat(prev)
                    }
                    return curr
                }, [])

                localStorage.setItem('menus', JSON.stringify(_muen))
                _userStore.auth = auth
                const newRoutes = getRoutes(newArr)
                for (const route of newRoutes) {
                    router.addRoute('layout', { ...route })
                }
                hasRoles = false
                routeStore.resetRoutes()
                router.addRoute({ path: '/:catchAll(.*)', redirect: '/404' })
                next({ ...to, replace: true })
            } else {
                const _userStore = userStore(pinia)
                document.title = `企管家WEB-${to.meta.title}`
                _userStore.joinToUsed(to)
                routeStore.addRoutes(to)
                next()
            }
        }
    } else {
        if (whiteList.includes(to.path)) {
            hasRoles = true
            next()
        } else {
            ElMessage.error('检测到你未登陆请先登陆！')
            next('/login')
        }
    }
})


// 重置路由
const newRouter = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

export function resetRouter() {
    router.matcher = newRouter.matcher
}


export default router